class GradeTable {
    constructor(containerId) {
        this.container = document.createElement('div');
        this.container.className = 'table-container';
        document.getElementById(containerId).appendChild(this.container);

        // 班级信息输入
        this.classInfoDiv = document.createElement('div');
        this.classInfoDiv.className = 'mb-3';
        this.classInfoDiv.innerHTML = `
            <input type="text" class="form-control mb-2" placeholder="请输入班级名称">
            <div class="btn-group">
                <button class="btn btn-info add-column">添加成绩列</button>
                <button class="btn btn-danger remove-table">删除表格</button>
            </div>
        `;
        this.container.appendChild(this.classInfoDiv);

        // 创建表格容器
        this.tableDiv = document.createElement('div');
        this.container.appendChild(this.tableDiv);

        // 初始化HandsonTable
        this.hot = new Handsontable(this.tableDiv, {
            data: [['', '']],  // 初始只有一行
            colHeaders: true,  // 修改这里，启用列头
            columns: [
                { type: 'text', title: '学号' },
                { type: 'text', title: '姓名' }
            ],
            minSpareRows: 1,
            rowHeaders: true,
            contextMenu: true,
            height: 'auto',
            licenseKey: 'non-commercial-and-evaluation' // 添加许可证密钥
        });

        // 绑定事件
        this.bindEvents();
    }

    bindEvents() {
        // 添加成绩列按钮
        this.container.querySelector('.add-column').addEventListener('click', () => {
            const modal = new bootstrap.Modal(document.getElementById('subjectModal'));
            window.currentEditingTable = this;  // 保存当前正在编辑的表格引用
            modal.show();
        });

        // 删除表格按钮
        this.container.querySelector('.remove-table').addEventListener('click', () => {
            if (confirm('确定要删除这个班级的成绩表格吗？')) {
                this.container.remove();
            }
        });
    }

    addSubjectColumn(subject, date) {
        const columnHeader = `${subject}\n${date}`;
        const currentColumns = [...this.hot.getSettings().columns];
        currentColumns.push({ type: 'numeric', title: columnHeader });
        
        this.hot.updateSettings({
            columns: currentColumns
        });
    }

    getData() {
        return {
            className: this.container.querySelector('input').value,
            headers: this.hot.getSettings().columns.map(col => col.title),
            data: this.hot.getData()
        };
    }
}

// 全局变量和事件处理
let tables = [];

document.getElementById('addTable').addEventListener('click', () => {
    tables.push(new GradeTable('tables-container'));
});

document.getElementById('confirmAddSubject').addEventListener('click', () => {
    const subject = document.getElementById('subjectName').value;
    const date = document.getElementById('examDate').value;
    
    if (subject && date && window.currentEditingTable) {
        window.currentEditingTable.addSubjectColumn(subject, date);
        bootstrap.Modal.getInstance(document.getElementById('subjectModal')).hide();
        document.getElementById('subjectName').value = '';
        document.getElementById('examDate').value = '';
    } else {
        alert('请填写完整信息');
    }
});

document.getElementById('saveData').addEventListener('click', async () => {
    const data = tables.map(table => table.getData());
    
    try {
        const response = await fetch('/save_grades', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        
        if (response.ok) {
            alert('保存成功！');
        } else {
            alert('保存失败，请重试！');
        }
    } catch (error) {
        console.error('保存失败:', error);
        alert('保存失败，请检查网络连接！');
    }
});

// 页面加载时获取已有数据
window.addEventListener('DOMContentLoaded', async () => {
    try {
        const response = await fetch('/get_grades');
        if (response.ok) {
            const data = await response.json();
            data.forEach(classData => {
                const table = new GradeTable('tables-container');
                table.container.querySelector('input').value = classData.className;
                
                const settings = table.hot.getSettings();
                settings.colHeaders = true;
                settings.columns = classData.headers.map(header => 
                    header === '学号' || header === '姓名' ? { type: 'text', title: header } : { type: 'numeric', title: header }
                );
                table.hot.updateSettings(settings);
                table.hot.loadData(classData.data);
                
                tables.push(table);
            });
        }
    } catch (error) {
        console.error('加载数据失败:', error);
    }
});
